package com.jg.ads.ad;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;

import com.jg.ads.R;
import com.jg.ads.adapter.TestAdapter;
import com.jg.ads.constant.JgAdsDemoConstant;
import com.jg.ads.utils.MyDisplayUtil;
import com.jg.ads.utils.SPUtil;
import com.jg.ads.widget.MySmartRefreshLayout;
import com.junion.ad.SuspendAd;
import com.junion.ad.bean.SuspendAdInfo;
import com.junion.ad.entity.AdSize;
import com.junion.ad.error.JUnionError;
import com.junion.ad.listener.SuspendAdListener;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import java.util.ArrayList;
import java.util.List;

/**
 * @author maipian
 * @description 描述
 * @date 2025/6/10
 */
public class SuspensionAdActivity extends AppCompatActivity {
    private MySmartRefreshLayout refreshLayout;
    private RecyclerView recyclerView;

    private FrameLayout flContainer;

    /**
     * 测试数据适配器
     */
    private TestAdapter mTestAdapter;
    /**
     * 测试数据数组
     */
    private List<Object> mTempDataList = new ArrayList<>();
    /**
     * 下拉刷新类型
     */
    private int mRefreshType;

    /**
     * 最后滑动列表时的类型
     */
    private int mLastScrollState = RecyclerView.SCROLL_STATE_IDLE;

    private SuspendAd mSuspensionAd;

    private int autoRefreshInterval = 15;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_suspension_ad);

        autoRefreshInterval = SPUtil.getInt(SuspensionAdActivity.this, "SuspensionAutoRefreshInterval", 10);
        ((EditText) findViewById(R.id.etRefreshTime)).setText(autoRefreshInterval + "");

        initView();
        initAdapter();
        initListener();

        initRefreshView();

        loadSuspensionAd();
    }

    private void initView() {
        recyclerView = findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        refreshLayout = findViewById(R.id.refreshLayout);

        flContainer = findViewById(R.id.flContainer);
    }

    private void initAdapter() {
        mTestAdapter = new TestAdapter();
        recyclerView.setAdapter(mTestAdapter);
    }

    private void initListener() {
        // 下拉刷新上拉加载监听
        if (refreshLayout != null) {
            refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
                @Override
                public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                    mRefreshType = MySmartRefreshLayout.TYPE_LOAD_MORE;
                    loadData();
                }

                @Override
                public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                    mRefreshType = MySmartRefreshLayout.TYPE_FRESH;
                    if (mTestAdapter != null) {
                        mTestAdapter.clearData();
                    }
                    loadData();
                }
            });
            refreshLayout.autoRefresh();
        }

        // 布局滑动监听
        if (recyclerView != null) {
            recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
                @Override
                public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                    super.onScrollStateChanged(recyclerView, newState);
                    if (mLastScrollState == RecyclerView.SCROLL_STATE_IDLE &&
                            (newState == RecyclerView.SCROLL_STATE_DRAGGING ||
                                    newState == RecyclerView.SCROLL_STATE_SETTLING)) {
                        // 从静止状态变为滚动状态：滚动开始
                        setRlSuspensionAdRightMargin(flContainer, - MyDisplayUtil.dp2px(56));
                        setRlSuspensionAdAlpha(flContainer, 0.5f);
                    } else if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                        // 滚动停止
                        setRlSuspensionAdRightMargin(flContainer, MyDisplayUtil.dp2px(16));
                        setRlSuspensionAdAlpha(flContainer, 1.0f);
                    }
                    // 更新状态
                    mLastScrollState = newState;
                }
            });
        }

    }

    /**
     * 加载测试数据
     */
    private void loadData() {
        mTempDataList.clear();
        for (int i = 0; i < 40; i++) {
            mTempDataList.add("模拟的普通数据 : " + (mTestAdapter == null ? 0 : mTestAdapter.getItemCount() + i));
        }
        if (mTestAdapter != null) {
            mTestAdapter.addData(mTempDataList);
        }
        new Handler(getMainLooper()).postDelayed(new Runnable() {
            @Override
            public void run() {
                if (refreshLayout != null) {
                    refreshLayout.finish(mRefreshType, true, false);
                }
            }
        }, 500);
    }

    private void initRefreshView() {
        findViewById(R.id.btnLoadAd).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String text = ((EditText) findViewById(R.id.etRefreshTime)).getText().toString().trim();
                try {
                    autoRefreshInterval = Integer.parseInt(text);
                    SPUtil.putInt(SuspensionAdActivity.this, "SuspensionAutoRefreshInterval", autoRefreshInterval);
                } catch (Exception e) {}
                loadSuspensionAd();
            }
        });
    }

    /**
     * 加载悬浮广告
     */
    public void loadSuspensionAd() {
        setRlSuspensionAdVisibility(flContainer, View.VISIBLE);
        mSuspensionAd = new SuspendAd(this, flContainer);
        mSuspensionAd.setAdSize(new AdSize(MyDisplayUtil.dp2px(80), MyDisplayUtil.dp2px(80)));
        mSuspensionAd.setAutoRefresh(autoRefreshInterval);
        mSuspensionAd.setListener(new SuspendAdListener() {
            @Override
            public void onAdReceive(SuspendAdInfo adInfo) {
            }

            @Override
            public void onAdExpose(SuspendAdInfo adInfo) {

            }

            @Override
            public void onAdClick(SuspendAdInfo adInfo) {

            }

            @Override
            public void onAdClose(SuspendAdInfo adInfo) {
                setRlSuspensionAdVisibility(flContainer, View.GONE);
                if (mSuspensionAd != null) {
                    mSuspensionAd.release();
                    mSuspensionAd = null;
                }
            }

            @Override
            public void onAdFailed(JUnionError error) {

            }
        });
        // 上线需要替换成自己当
        mSuspensionAd.loadAd(JgAdsDemoConstant.NATIVE_BID_ID);
    }

    /**
     * 设置广告布局是否可见
     * @param visibility
     */
    public void setRlSuspensionAdVisibility(ViewGroup view, int visibility) {
        if (view != null) {
            view.setVisibility(visibility);
        }
    }

    /**
     * 设置广告布局右边距
     * 滑动布局时可以将悬浮广告偏移
     * @param rightMarginPx
     */
    public void setRlSuspensionAdRightMargin(ViewGroup view, int rightMarginPx) {
        if (view != null) {
            RelativeLayout.LayoutParams suspensionAdParams = (RelativeLayout.LayoutParams) view.getLayoutParams();
            suspensionAdParams.rightMargin = rightMarginPx;
            view.setLayoutParams(suspensionAdParams);
        }
    }

    /**
     * 设置广告布局透明度
     * 滑动布局时可以将悬浮广告透明度降低
     * @param alpha
     */
    public void setRlSuspensionAdAlpha(ViewGroup view, float alpha) {
        if (view != null) {
            view.setAlpha(alpha);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mSuspensionAd != null) {
            mSuspensionAd.resume();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mSuspensionAd != null) {
            mSuspensionAd.pause();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mSuspensionAd != null) {
            mSuspensionAd.release();
            mSuspensionAd = null;
        }
    }
}
